<template>
  <div class="d-upload">
    <a-upload-dragger name="file" :action="upurl" :data="parameter" :headers="headers" :beforeUpload="beforeUpload" @change="handleChange">
      <p class="ant-upload-drag-icon">
        <inbox-outlined />
      </p>
      <p class="ant-upload-hint">单击或拖动文件到该区域以上传</p>
    </a-upload-dragger>
  </div>
</template>
<script lang='ts'>
import { InboxOutlined } from "@/components/AntDesign/icons/icons";
import AppInfoParser from "app-info-parser";
import { reactive, SetupContext, toRefs } from "vue";
import { $message } from "@/components/AntDesign/message";
export default {
  components: {
    InboxOutlined,
  },
  props: {
    upurl: String,
    type: {
      type: String,
      default: "ipa",
    },
  },
  emits: ["routerPush"],
  setup(props: any, ctx: SetupContext) {
    const data = reactive({
      parameter: {},
      headers: {
        Authorization: localStorage.getItem("token") as string,
      },
    });
    function handleChange(info: any) {
      const status: string = info.file.status;
      if (status === "done") {
        ctx.emit("routerPush");
        $message("success", info.file.response.message);
      } else if (status === "error") {
        $message("error", info.file.response.message);
      }
    }
    async function beforeUpload(file: any): Promise<void> {
      if (file.name.indexOf(props.type) === -1) {
        $message("error", `请上传${props.type}类型的包`);
        throw `请上传${props.type}类型的包`;
      }

      const parser: any = await new AppInfoParser(file);
      const res: any = await parser.parse();
      console.log(res);

      data.parameter = {
        name: appname(res),
        package: res.CFBundleIdentifier || res.package,
        build: res.CFBundleVersion || res.versionCode,
        version: res.CFBundleShortVersionString || res.versionName,
        imgData: res.icon,
      };
    }

    const appname = (res: any) => {
      if (
        res.CFBundleDisplayName ||
        res.CFBundleName ||
        res.CFBundleExecutable
      ) {
        return (
          res.CFBundleDisplayName || res.CFBundleName || res.CFBundleExecutable
        );
      } else {
        return Array.isArray(res.application.label)
          ? res.application.label[0]
          : res.application.label;
      }
    };

    return {
      ...toRefs(data),
      beforeUpload,
      handleChange,
    };
  },
};
</script>
<style lang="less" scoped>
.d-upload {
  width: 30%;
  height: 200px;
  margin: 50px auto;
}
</style>
